<?php

include_once('viper/autoloader.php');

class viper_server_similarFeatures {
  public static $n = 100;
  public static $m = 50;
  public static $f = 10;
  public static $thres = 7;
  
  // DO NO alter $result
  private static function VoteOnFeatures($top_raters, &$result) {
    $m = self::$m;
    $thres = self::$thres;
    
    $votes = array();    
    // Loop through features, then the voters    
    $nraters = count($top_raters);
    for ($i = 0; $i < $m; $i++) {
      $vote_cur = 0;
      for ($idx = 0; $idx < $nraters; $idx++) {
        $voter_cur = $top_raters[$idx];
        if ($result[$voter_cur]['feature'.$i] >= $thres) {
          $vote_cur++;
        }
      }
      $votes['feature'.$i] = $vote_cur;
    }
    
    asort($votes);
    $votes = array_reverse($votes, true);
    
    return $votes;
  }
  
  public static function FindSimilarFeatures($userid, $feature) {
    $n = self::$n;
    $m = self::$m;
    $f = self::$f;
    $thres = self::$thres;
    
    $friends = viper_server_dbOps::ReadFromUserQuicklist();
    $result = viper_server_dbOps::ReadFromUserFeatureScoreDatabase();
    
    // Find the close friends who also like this feature
    $top_raters = array();
    for ($friend_idx = 0; $friend_idx < $f; $friend_idx++) {
      $friend = $friends[$userid]['friend'.$friend_idx];
      if ($friend == -1)
        break;
      if ($result[$friend]['feature'.$feature] >= $thres) {
        $top_raters[] = $friend;
      }
    }
    
    if (count($top_raters) == 0) {
      // Deal with the case where non of the friends like the feature
      // Output global similars
      $features_best = self::VoteOnFeatures(range(0, 49), $result);
    }
    else {
      // Ouput local similars
      $features_best = self::VoteOnFeatures($top_raters, $result);
    }
    
    return $features_best;
  }
}
 